<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StudentSubjectService
{
    // 列表查询
    public static function index($data)
    {
        $limit = isset($data['limit']) ? $data['limit'] : 10;

        $studio = \app\admin\model\StudentSubject::field('subject_id,subject_name,abbreviation,color')
            ->order('subject_id', 'desc')
            ->paginate($limit);

        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // 单条保存
    public static function save($data)
    {
        $validate = new Validate([
            'category_id' => 'require',
            'subject_name' => 'require',
            'abbreviation' => 'require',
            'color' => 'require',
        ], [
            'category_id.require' => 'CategoryId is not empty',
            'subject_name.require' => 'Subject Name is not empty',
            'abbreviation.require' => 'Abbreviation is not empty',
            'color.require' => 'Color is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        try {
            Db::startTrans();

            if(isset($data['subject_id']) && $data['subject_id']){
                $validate = new Validate(['subject_id' => 'require'], ['subject_id.require' => 'SubjectId is not empty']);
                if (!$validate->check($data)) {
                    return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
                }
                $result = \app\admin\model\StudentSubject::update($data);
            }else{
                $result = \app\admin\model\StudentSubject::create($data);
            }

            Db::commit();
            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];

        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 批量保存
    public static function save_new($data)
    {
//        return $data;
        $category_id = $data['category_id'];
        $results = [
            'subjects' => [],
            'levels' => [],
            'sub_categories' => [],
            'semesters' => [],
            'lessons' => []
        ];
        $errors = [];

        Db::startTrans();
        try {
            // 1. 处理子分类数据 (新增)
            if (!empty($data['sub_category']) && is_array($data['sub_category'])) {
                foreach ($data['sub_category'] as $subCatItem) {
                    $subCatItem['category_id'] = $category_id;
                    $subCatResult = self::processSubCategory($subCatItem);

                    if ($subCatResult['code'] != 200) {
                        $errors[] = 'SubCategory error: ' . ($subCatResult['msg'] ?? 'Unknown error');
                        continue;
                    }

                    $subcatId = $subCatItem['subcat_id'] ?? $subCatResult['data']->subcat_id;
                    $results['sub_categories'][] = $subCatResult['data'] ?? null;

                    // 处理该子分类下的级别
                    if (!empty($subCatItem['level']) && is_array($subCatItem['level'])) {
                        foreach ($subCatItem['level'] as $levelItem) {
                            $levelItem['subcat_id'] = $subcatId;
                            $levelItem['category_id'] = $category_id;
                            $levelResult = self::processLevel($levelItem);

                            if ($levelResult['code'] != 200) {
                                $errors[] = 'Level error: ' . ($levelResult['msg'] ?? 'Unknown error');
                            } else {
                                // 确保将结果添加到 $results['levels'] 中
                                $results['levels'][] = $levelResult['data'] ?? null;
                                // 调试输出，可以后续删除
                                \think\Log::write('Level saved: '.json_encode($levelResult['data']));
                            }
                        }
                    }

                    // 处理该子分类下的学期
                    if (!empty($subCatItem['semesters']) && is_array($subCatItem['semesters'])) {
                        foreach ($subCatItem['semesters'] as $semesterItem) {
                            $semesterItem['subcat_id'] = $subcatId;
                            $semesterItem['category_id'] = $category_id;
                            $semesterResult = self::processSemester($semesterItem);

                            if ($semesterResult['code'] != 200) {
                                $errors[] = 'Semester error: ' . ($semesterResult['msg'] ?? 'Unknown error');
                                continue;
                            }

                            $semesterId = $semesterItem['semester_id'] ?? $semesterResult['data']->semester_id;
                            $results['semesters'][] = $semesterResult['data'] ?? null;

                            // 处理课程
                            if (!empty($semesterItem['lesson_code']) && is_array($semesterItem['lesson_code'])) {
                                foreach ($semesterItem['lesson_code'] as $lessonItem) {
                                    $lessonItem['subcat_id'] = $subcatId;
                                    $lessonItem['semester_id'] = $semesterId;
                                    $lessonItem['category_id'] = $category_id;
                                    $lessonResult = self::processLesson($lessonItem);

                                    if ($lessonResult['code'] != 200) {
                                        $errors[] = 'Lesson error: ' . ($lessonResult['msg'] ?? 'Unknown error');
                                    } else {
                                        $results['lessons'][] = $lessonResult['data'] ?? null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 2. 处理无子分类的情况 (保留原有逻辑)
            else {
                // 处理学科
                if (!empty($data['subject']) && is_array($data['subject'])) {
                    foreach ($data['subject'] as $item) {
                        $item['category_id'] = $category_id;
                        $result = self::processSubject($item);
                        if ($result['code'] != 200) {
                            $errors[] = 'Subject error: ' . ($result['msg'] ?? 'Unknown error');
                        } else {
                            $results['subjects'][] = $result['data'] ?? null;
                        }
                    }
                }

                // 处理级别
                if (!empty($data['level']) && is_array($data['level'])) {
                    foreach ($data['level'] as $item) {
                        $item['category_id'] = $category_id;
                        $result = self::processLevel($item);
                        if ($result['code'] != 200) {
                            $errors[] = 'Level error: ' . ($result['msg'] ?? 'Unknown error');
                        } else {
                            $results['levels'][] = $result['data'] ?? null;
                        }
                    }
                }

                // 处理学期
                if (!empty($data['semesters']) && is_array($data['semesters'])) {
                    foreach ($data['semesters'] as $semesterItem) {
                        $semesterItem['category_id'] = $category_id;
                        $semesterResult = self::processSemester($semesterItem);

                        if ($semesterResult['code'] != 200) {
                            $errors[] = 'Semester error: ' . ($semesterResult['msg'] ?? 'Unknown error');
                            continue;
                        }

                        $semesterId = $semesterItem['semester_id'] ?? $semesterResult['data']->semester_id;
                        $results['semesters'][] = $semesterResult['data'] ?? null;

                        // 处理课程
                        if (!empty($semesterItem['lesson_code']) && is_array($semesterItem['lesson_code'])) {
                            foreach ($semesterItem['lesson_code'] as $lessonItem) {
                                $lessonItem['semester_id'] = $semesterId;
                                $lessonItem['category_id'] = $category_id;
                                $lessonResult = self::processLesson($lessonItem);

                                if ($lessonResult['code'] != 200) {
                                    $errors[] = 'Lesson error: ' . ($lessonResult['msg'] ?? 'Unknown error');
                                } else {
                                    $results['lessons'][] = $lessonResult['data'] ?? null;
                                }
                            }
                        }
                    }
                }
            }

            // 错误处理
            if (!empty($errors)) {
                Db::rollback();
                return [
                    'code' => 400,
                    'msg' => implode('; ', $errors),
                    'state' => 'PARTIAL_FAILURE',
                    'data' => $results
                ];
            }

            Db::commit();
            return [
                'code' => 200,
                'msg' => 'Data processed successfully',
                'state' => 'OK',
                'data' => $results
            ];

        } catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => 500,
                'msg' => 'System error: ' . $e->getMessage(),
                'state' => 'SYSTEM_ERROR',
                'data' => null
            ];
        }
    }

    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();

        if (empty($data['subject_id']) || !is_numeric($data['subject_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        try {
            Db::startTrans();
            $result = \app\admin\model\StudentSubject::destroy($data['subject_id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 下拉查询
    public static function select()
    {
        $studio = \app\admin\model\StudentSubject::field('subject_id,subject_name,abbreviation')
            ->order('subject_id', 'desc')
            ->select();

        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // ===== 新增子分类处理方法 =====
    private static function processSubCategory($item)
    {
        // 定义允许的字段
        $allowedFields = ['subcat_id', 'category_id', 'subcat_name', 'is_del'];

        // 过滤数据，只保留允许的字段
        $filteredItem = array_intersect_key($item, array_flip($allowedFields));

        // 确保category_id存在
        if (!isset($filteredItem['category_id'])) {
            return [
                'code' => 400,
                'msg' => 'category_id is required for subcategory',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        $validate = new Validate([
            'subcat_id' => 'number|gt:0',
            'category_id' => 'require|number',
            'subcat_name' => 'require',
            'is_del' => 'in:0,1'
        ], [
            'subcat_id.number' => 'subcat_id must be a positive integer',
            'subcat_id.gt' => 'subcat_id must be greater than 0',
            'category_id.require' => 'category_id is required',
            'category_id.number' => 'category_id must be a number',
            'subcat_name.require' => 'subcat_name is required',
            'is_del.in' => 'is_del must be 0 or 1'
        ]);

        if (!$validate->check($filteredItem)) {
            return [
                'code' => 400,
                'msg' => 'Invalid format for subcategory data: '.$validate->getError(),
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        try {
            if (isset($filteredItem['is_del']) && $filteredItem['is_del'] == 1 && isset($filteredItem['subcat_id'])) {
                // 删除子分类及关联数据
                self::deleteSubCategoryData($filteredItem['subcat_id']);
                return ['code' => 200];
            } elseif (isset($filteredItem['subcat_id'])) {
                // 更新
                if (isset($filteredItem['is_del'])) {
                    unset($filteredItem['is_del']);
                }
                $result = \app\admin\model\SubCategory::update($filteredItem);
            } else {
                // 新建
                if (isset($filteredItem['is_del'])) {
                    unset($filteredItem['is_del']);
                }
                $result = \app\admin\model\SubCategory::create($filteredItem);
            }
            return ['code' => 200, 'data' => $result ?? null];
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => 'SubCategory processing failed: '.$e->getMessage()];
        }
    }

    // ===== 原有数据处理方法 (补充subcat_id支持) =====
    private static function processSubject($item)
    {
        $validate = new Validate([
            'subject_id' => 'number|gt:0',
            'category_id' => 'require|number',
            'subcat_id' => 'number',
            'subject_name' => 'require',
            'abbreviation' => 'require|alphaNum',
            'color' => 'require|regex:/^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/',
            'is_del' => 'in:0,1'
        ], [
            'subject_id.number' => 'subject_id must be a positive integer',
            'subject_id.gt' => 'subject_id must be greater than 0',
            'category_id.require' => 'category_id is required',
            'category_id.number' => 'category_id must be a number',
            'subcat_id.number' => 'subcat_id must be a number',
            'subject_name.require' => 'subject_name is required',
            'abbreviation.require' => 'abbreviation is required',
            'abbreviation.alphaNum' => 'abbreviation must contain only letters and numbers',
            'color.require' => 'color is required',
            'color.regex' => 'color must be in hexadecimal code',
            'is_del.in' => 'is_del must be 0 or 1'
        ]);

        if (!$validate->check($item)) {
            return [
                'code' => 400,
                'msg' => 'Invalid format for subject data: '.$validate->getError(),
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        try {
            if (isset($item['is_del']) && $item['is_del'] == 1 && isset($item['subject_id'])) {
                \app\admin\model\StudentSubject::destroy($item['subject_id']);
            } elseif (isset($item['subject_id'])) {
                if (isset($item['is_del'])) unset($item['is_del']);
                $result = \app\admin\model\StudentSubject::update($item);
            } else {
                if (isset($item['is_del'])) unset($item['is_del']);
                $result = \app\admin\model\StudentSubject::create($item);
            }
            return ['code' => 200, 'data' => $result ?? null];
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => 'Subject processing failed: '.$e->getMessage()];
        }
    }

    private static function processLevel($item)
    {
        // 定义允许的字段
        $allowedFields = ['level_id', 'category_id', 'subcat_id', 'level_name', 'abbreviation', 'age_range', 'is_del'];

        // 过滤数据，只保留允许的字段
        $filteredItem = array_intersect_key($item, array_flip($allowedFields));

        // 确保category_id和subcat_id存在
        if (!isset($filteredItem['category_id'])) {
            return [
                'code' => 400,
                'msg' => 'category_id is required for level',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        if (!isset($filteredItem['subcat_id'])) {
            return [
                'code' => 400,
                'msg' => 'subcat_id is required for level',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        $validate = new Validate([
            'level_id' => 'number|gt:0',
            'category_id' => 'require|number',
            'subcat_id' => 'require|number',
            'level_name' => 'require',
            'abbreviation' => 'require|alphaNum',
            'age_range' => 'chsAlphaNum',
            'is_del' => 'in:0,1'
        ], [
            'level_id.number' => 'level_id must be a number',
            'level_id.gt' => 'level_id must be positive',
            'category_id.require' => 'category_id is required',
            'category_id.number' => 'category_id must be a number',
            'subcat_id.require' => 'subcat_id is required',
            'subcat_id.number' => 'subcat_id must be a number',
            'level_name.require' => 'level_name is required',
            'abbreviation.require' => 'abbreviation is required',
            'abbreviation.alphaNum' => 'abbreviation must be alphanumeric',
            'age_range.chsAlphaNum' => 'age_range must contain only Chinese characters, letters and numbers',
            'is_del.in' => 'is_del must be 0 or 1'
        ]);

        if (!$validate->check($filteredItem)) {
            return [
                'code' => 400,
                'msg' => 'Invalid format for level data: '.$validate->getError(),
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        try {
            if (isset($filteredItem['is_del']) && $filteredItem['is_del'] == 1 && isset($filteredItem['level_id'])) {
                \app\admin\model\StudentCourseLevel::destroy($filteredItem['level_id']);
                return ['code' => 200];
            } elseif (isset($filteredItem['level_id'])) {
                if (isset($filteredItem['is_del'])) unset($filteredItem['is_del']);
                $result = \app\admin\model\StudentCourseLevel::update($filteredItem);
            } else {
                if (isset($filteredItem['is_del'])) unset($filteredItem['is_del']);
                $result = \app\admin\model\StudentCourseLevel::create($filteredItem);
            }
            return ['code' => 200, 'data' => $result ?? null];
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => 'Level processing failed: '.$e->getMessage()];
        }
    }

    private static function processSemester($item)
    {
        // 定义允许的字段
        $allowedFields = ['semester_id', 'category_id', 'subcat_id', 'semester_name', 'is_del'];

        // 过滤数据，只保留允许的字段
        $filteredItem = array_intersect_key($item, array_flip($allowedFields));

        // 确保category_id和subcat_id存在
        if (!isset($filteredItem['category_id'])) {
            return [
                'code' => 400,
                'msg' => 'category_id is required for semester',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        if (!isset($filteredItem['subcat_id'])) {
            return [
                'code' => 400,
                'msg' => 'subcat_id is required for semester',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        $validate = new Validate([
            'semester_id' => 'number|gt:0',
            'category_id' => 'require|number',
            'subcat_id' => 'require|number',
            'semester_name' => 'require',
            'is_del' => 'in:0,1'
        ], [
            'semester_id.number' => 'semester_id must be a positive integer',
            'semester_id.gt' => 'semester_id must be greater than 0',
            'category_id.require' => 'category_id is required',
            'category_id.number' => 'category_id must be a number',
            'subcat_id.require' => 'subcat_id is required',
            'subcat_id.number' => 'subcat_id must be a number',
            'semester_name.require' => 'semester_name is required',
            'is_del.in' => 'is_del must be 0 or 1'
        ]);

        if (!$validate->check($filteredItem)) {
            return [
                'code' => 400,
                'msg' => 'Invalid format for semester data: '.$validate->getError(),
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        try {
            if (isset($filteredItem['is_del']) && $filteredItem['is_del'] == 1 && isset($filteredItem['semester_id'])) {
                $lessons = \app\admin\model\StudentLessonCodes::where(['semester_id'=>$filteredItem['semester_id']])->select();
                if($lessons){
                    foreach($lessons as $lesson){
                        \app\admin\model\StudentLessonCodes::destroy($lesson['lesson_id']);
                    }
                }
                \app\admin\model\StudentSemester::destroy($filteredItem['semester_id']);
                return ['code' => 200];
            } elseif (isset($filteredItem['semester_id'])) {
                if (isset($filteredItem['is_del'])) unset($filteredItem['is_del']);
                $result = \app\admin\model\StudentSemester::update($filteredItem);
            } else {
                if (isset($filteredItem['is_del'])) unset($filteredItem['is_del']);
                $result = \app\admin\model\StudentSemester::create($filteredItem);
            }
            return ['code' => 200, 'data' => $result];
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => 'Semester processing failed: '.$e->getMessage()];
        }
    }

    private static function processLesson($item)
    {
        // 定义允许的字段
        $allowedFields = ['lesson_id', 'semester_id', 'category_id', 'subcat_id', 'code', 'is_del'];

        // 过滤数据，只保留允许的字段
        $filteredItem = array_intersect_key($item, array_flip($allowedFields));

        // 确保必填字段存在
        if (!isset($filteredItem['semester_id'])) {
            return [
                'code' => 400,
                'msg' => 'semester_id is required for lesson',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        if (!isset($filteredItem['category_id'])) {
            return [
                'code' => 400,
                'msg' => 'category_id is required for lesson',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        if (!isset($filteredItem['subcat_id'])) {
            return [
                'code' => 400,
                'msg' => 'subcat_id is required for lesson',
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        $validate = new Validate([
            'lesson_id' => 'number|gt:0',
            'semester_id' => 'require|number|gt:0',
            'category_id' => 'require|number',
            'subcat_id' => 'require|number',
            'code' => 'require',
            'is_del' => 'in:0,1'
        ], [
            'lesson_id.number' => 'lesson_id must be a positive integer',
            'lesson_id.gt' => 'lesson_id must be greater than 0',
            'semester_id.require' => 'semester_id is required',
            'semester_id.number' => 'semester_id must be a positive integer',
            'semester_id.gt' => 'semester_id must be greater than 0',
            'category_id.require' => 'category_id is required',
            'category_id.number' => 'category_id must be a number',
            'subcat_id.require' => 'subcat_id is required',
            'subcat_id.number' => 'subcat_id must be a number',
            'code.require' => 'code is required',
            'is_del.in' => 'is_del must be 0 or 1'
        ]);

        if (!$validate->check($filteredItem)) {
            return [
                'code' => 400,
                'msg' => 'Invalid format for lesson data: '.$validate->getError(),
                'state' => 'INVALID_ARGUMENT'
            ];
        }

        try {
            if (isset($filteredItem['is_del']) && $filteredItem['is_del'] == 1 && isset($filteredItem['lesson_id'])) {
                \app\admin\model\StudentLessonCodes::destroy($filteredItem['lesson_id']);
            } elseif (isset($filteredItem['lesson_id'])) {
                if (isset($filteredItem['is_del'])) unset($filteredItem['is_del']);
                $result = \app\admin\model\StudentLessonCodes::update($filteredItem);
            } else {
                if (isset($filteredItem['is_del'])) unset($filteredItem['is_del']);
                $result = \app\admin\model\StudentLessonCodes::create($filteredItem);
            }
            return ['code' => 200, 'data' => $result ?? null];
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => 'Lesson processing failed: '.$e->getMessage()];
        }
    }

    // ===== 私有辅助方法 =====
    private static function deleteSubCategoryData($subcatId)
    {
        // 删除关联的级别
        \app\admin\model\StudentCourseLevel::where('subcat_id', $subcatId)->delete();

        // 删除关联的学期及课程
        $semesters = \app\admin\model\StudentSemester::where('subcat_id', $subcatId)->select();
        foreach ($semesters as $semester) {
            \app\admin\model\StudentLessonCodes::where('semester_id', $semester['semester_id'])->delete();
        }
        \app\admin\model\StudentSemester::where('subcat_id', $subcatId)->delete();

        // 最后删除子分类
        \app\admin\model\SubCategory::destroy($subcatId);
    }
}
